<route lang="json5" type="page">
{
	style: {
		navigationStyle: 'custom',
		navigationBarTitleText: '小倍问答'
	},
}
</route>

<template>
	<view class="talk">
		<image class="back" @tap="goHome"  src="https://nx-hb-k12-test.oss-cn-hangzhou.aliyuncs.com/goods_detail/202312/20231207193009_65713c4184e55.png" mode=""></image>
	   <scroll-view class="talkBox" :scroll-top="scrollTop" scroll-y="true" @scroll="scroll">
		   <view class="top">
			   <view>你好，我是阅读助手小倍!</view>
			   <view>请问有什么可以帮助的吗？</view>
		   </view>
		  <!-- <image src="../../static/loading.webp" mode="" style="width: 100rpx;height: 80rpx;"></image> -->
		   <view class='one' v-for="(item,index) in talks" :key='index'>
			   <view class="text" :class="{ 'bai': item.who == 'bai', 'mex': item.who == 'me' , 'sound': item.who == 'sound' }" @tap="soundSpeck(item)">
				   <block v-if="item.who !== 'sound'">{{item.text}}</block>
				   <block v-if="item.who == 'sound'">
					   <image src="../../static/sound.png" class="soundImg" v-show="item.start"></image>
					  <image src="../../static/soundOne.png" class="soundImg" v-show="!item.start"></image>
				   </block>
				</view>
		   </view>
	   </scroll-view>
	   <view class="inputBox">
		   <view class="headBox" @tap='changeType'>
			   <image src="../../static/audio.png" mode="" class="iconImg" v-show='inType'></image>
			   <image src="../../static/write.png" mode="" class="iconImg" v-show='!inType'></image>
		   </view>
		   <view class="input">
			   <input type="text" placeholder='请输入' v-if='inType' v-model="myTalk"/>
			   <view class="audioBtn" v-if="!inType" @touchstart="touchstart" @touchend="onTouchEnd">
				   <text v-show="!soundOff">按住说话</text>
				   <image src="../../static/sound.png" v-show="soundOff" class="soundImg"></image>
				</view>
			</view>
		   <view class="btn" @tap="sent">发送</view>
	   </view>
	</view>
</template>

<script lang="ts" setup>
import { log } from 'console';
import { getTalkItem, getTalkItemAudio } from '@/service/talk';
import { useUserStore } from '@/store';
import { storeToRefs } from 'pinia';
// let talks = ref([]);
let myTalk = ref('');
let talk_id = ref('');
let talks = ref([]);
let inType = ref(true);
let soundOff = ref(false);
let scrollTop = ref(999999999999999);

const userStore = useUserStore();
const recoder = wx.getRecorderManager();
const obj = storeToRefs(userStore);
let task;

onShow(() => {
	// console.log()
	const uid = obj.uid.value;
    console.log('初始uid',uid)
	// uid.toString()
	task = wx.connectSocket({
	    url: 'wss://msg.diyi.cn:8443', // 你的WebSocket服务器地址
	  });
	  
	task.onOpen(() => {
	   console.log('打开了链接'+uid)
	  task.send({
		  data: String(uid),
		  success:() => {
			  console.log('发送成功');
		  },
		  fail:() => {
			  console.log('发送失败');
		  }
	  })
	  
	  task.onMessage((res) => {
	     console.log('收到的',res)
	     if(res.data) {
	  	   uni.hideLoading();
	  	   const resObj = JSON.parse(res.data)
	  	   const index = getBaidu(resObj.msg_id);
	  	   if (index === '') {
	  		   talks.value.push({
	  		   	 who:'bai',
	  		   	 text:resObj.msg,
	  		   	 msg_id:resObj.msg_id
	  		   });
	  	   } else {
	  		   const num = Number(index);
	  		   setTimeout(() => {
	  			    talks.value[num].text += resObj.msg;
	  				 scrollTop.value = scrollTop.value + 1;
	  		   },200)
	  	   }
	     }
	  })
	})
	
	
	
	
	task.onError((errMsg) => {
		console.log(JSON.stringify(errMsg))
	})
	

	// task.onMessage(function(res) {
	//   
	// });
	// wx.onSocketOpen(function(res) {
	//   console.log('WebSocket连接已打开！');
	// });
	
	// task.onClose((res) => {
	// 	console.log('服务器已关闭：',res);
	// })
	
});

onUnload(() => {
   console.log('onUnload')
	task.close({
		code:1000,
		reason:'关闭',
		success:() => {
		  console.log('关闭成功');
		},
		fail:(err) => {
		  console.log('关闭失败:'+ err);
		}
	})
})


onHide(() => {
	console.log('onHide')
	task.close({
		code:1000,
		reason:'关闭',
		success:() => {
	      console.log('关闭成功');
		},
		fail:(err) => {
		  console.log('关闭失败:'+ err);
		}
	})
});

const getBaidu = (id:any) => {
	let talkIndex:Number | String = '';
	talks.value.forEach((item,index) => {
		if ( item.msg_id == id) {
			talkIndex = index
		}
	}) 
	return  talkIndex;
}


const soundSpeck = (item:any) => {
    const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.src = item.text;
	item.start = true;
	innerAudioContext.play();
	innerAudioContext.onEnded(() => {
	  item.start = false;
	});
}

const sent = async () => {
	if(myTalk.value === "") {
		return;
	}
	 //console.log(myTalk.value);
      // console.log(scrollTop);
	 talks.value.push({
		 who:'me',
		 text:myTalk.value
	 });
	
	 scrollTop.value = scrollTop.value + 1;
	 // console.log(talks.value);
	 uni.showLoading({
	 	title:'小倍思考中',
		icon:'none'
	 })
	const taltext =  myTalk.value;
	myTalk.value = '';
	const res = await getTalkItem({
		id:talk_id.value,
		keyword:taltext,
		stream:true
	});
	 console.log(res);
	if (res) {
		// console.log(res);
		talk_id.value = res.data.id;
		
		// talks.value.push({
		// 	 who:'bai',
		// 	 text:res.data.answer
		// });
		
	}
};

recoder.onStop( async (res) => {
  // console.log('recorder stop', res)
  const { tempFilePath } = res;
  talks.value.push({
  	  who:'sound',
  	  text:tempFilePath,
  	  start:false
  }) 
  scrollTop.value = scrollTop.value + 1;
  uni.showLoading({
  	title:'小倍思考中',
  		icon:'none'
  })
  
  uni.uploadFile({
  	url: import.meta.env.VITE_SERVER_BASEURL + '/api/ai/file_upload',
  	filePath: tempFilePath,
  	name: 'file',
	formData: {
		'id':talk_id.value,
		'stream':1
	},
  	success:(res) => {
  		console.log("上传成功",res);
		// const data = JSON.parse(res.data);
		// console.log(data)
		// if (data.data.answer) {
		// 	talks.value.push({
		// 		 who:'bai',
		// 		 text:data.data.answer
		// 	});
		// }
		// scrollTop.value = scrollTop.value + 1;
		
  	},
  	fail:(err) => {
  		console.log("上传失败",err);
  	}
  });
  
  // const data = await getTalkItemAudio({
  // 	id:talk_id.value,
  // 	file:tempFilePath
  // });
  // if(data) {
	 // console.log(data)
  // }
})

const changeType = () => {
	inType.value = !inType.value;
}

const goHome = ()=> {
	uni.reLaunch({
		url:'/pages/index/index'
	})
}

const scroll = (e) => {
	console.log(e);
}

const touchstart = () => {
	soundOff.value = true;
	recoder.start({
		duration: 10000, //录音时长
		sampleRate: 16000,  //采样率
		numberOfChannels: 1, //录音通道数
		encodeBitRate: 24000,  //编码码率
		format:'wav',   //
		frameSize: 50    //指定帧大小
	});
};

const onTouchEnd = () => {
	soundOff.value = false;
	recoder.stop();
}
</script>
<style lang="scss" scoped>
.talk {
	width: 100vw;
	height: 100vh;
	position: relative;
	.back {
		width: 60rpx;
		height: 60rpx;
		position: fixed;
		left:50rpx;
		top:30rpx;
		z-index: 999999;
	}
	.talkBox {
		position: absolute;
		top:60rpx;
		left:0;
		bottom:120rpx;
		right: 0;
		padding: 35rpx;
		box-sizing: border-box;
		overflow-y: auto;
		// background-color: pink;
		.top {
			padding: 20rpx 30rpx;
			border-radius: 10rpx;
			// border:1px solid #ddd;
			line-height: 1.8;
			margin-bottom: 30rpx;
			background-color: #cfe7ff;
		}
		.one {
			overflow: hidden;
			margin-bottom: 30rpx;
			padding: 0rpx;
			.text {
				padding: 15rpx 25rpx;
				line-height: 1.8;
				max-width: 70%;
				border-radius: 10rpx;
				&.bai {
					float: left;
					background-color: #cfe7ff;
				}
				&.mex {
				    border:1px solid #ddd;
					float:right;
				}
				&.sound {
				    border:1px solid #ddd;
					line-height: 0;
					float:right;
				}
			}
		}
	}
	
	.soundImg {
		width: 50rpx;
		height: 50rpx;
	}
	
	.inputBox {
		position: absolute;
		left:0;
		bottom:0rpx;
		// height: 115rpx;
		right: 0;
		display: flex;
		padding:15rpx 25rpx 50rpx 15rpx;
		box-sizing: border-box;
		.headBox {
			.iconImg {
				width: 84rpx;
				height: 84rpx;
			}
		}
		
		.input {
			width: 442rpx;
			flex: none;
			// padding: 0 10rpx;
			margin-right: 20rpx;	
			margin-left: 10rpx;
			.audioBtn {
				width: 442rpx;
				height: 86rpx;
				background-color: #ddd;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 36rpx;
				color: #545252;
				
			}
			input {
				width: 100%;
				height: 100%;
				background-color: #ddd;
				border-radius: 8rpx;
				padding-left: 24rpx;
				padding-right: 24rpx;
				box-sizing: border-box;
			}
		}
		.btn {
			background-color: $uni-color-primary;
			color:#fff;
			height: 90rpx;
			width: 100rpx;
			border-radius: 8rpx;
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
}

</style>
